package com.bdsys.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bdsys.cache.ImageCache;
import com.bdsys.dao.ImageDAO;
import com.bdsys.domain.ImageDomain;

/**
 * Servlet implementation class DeviceImageServlet
 */
public class DeviceImageByDidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private static BeanFactory applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
	
	private static ImageDAO imagedao = (ImageDAO)applicationContext.getBean("imageDAO");
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeviceImageByDidServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String did = String.valueOf(request.getParameter("did"));
		String isShowAll = request.getParameter("showAll");
		OutputStream out = response.getOutputStream();
		if(!ImageCache.map.containsKey(did)){
			List<ImageDomain> list = imagedao.selectByDid(did);
			Map<String, ImageDomain> indexMap = new HashMap<String, ImageDomain>();
			for(int i = 0 ;i<list.size();i++){
				ImageDomain image = list.get(i);
				indexMap.put(String.valueOf(i), image);
			}
			
			ImageCache.map.put(did, indexMap);
		}
		
		Map<String, ImageDomain> indexMap = ImageCache.map.get(did);
		
		Set<String> set = indexMap.keySet();
		
		
		if (isShowAll == null) {
			for (String index : set) {
				ImageDomain image = indexMap.get(index);

				if ("1".equals(image.getDefalut())) {

					byte[] buf = image.getContent();
					for (int i = 0; i < buf.length; i++) {
						out.write(buf[i]);
					}

					break;
				}
			}
		} else {
			String index = request.getParameter("index");
			
			if (indexMap.containsKey(index)) {
				ImageDomain image = indexMap.get(index);
				

				byte[] buf = image.getContent();
				for (int i = 0; i < buf.length; i++) {
					out.write(buf[i]);
				}
			}
		}
			
			out.close();	
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
